# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone
import json
from commandes.models import Commande
from clients.models import Client
   
class Fournisseur(models.Model):
    nom = models.CharField(verbose_name=(u"Nhà cung cấp"),max_length=200, null=False, blank=False)
    adresse = models.CharField(verbose_name=(u"Địa chỉ"),max_length=200, null=True, blank=True)
    tel_fixe = models.CharField(verbose_name=(u"ĐT Bàn"), max_length=14, blank=True, default="")
    tel_port = models.CharField(verbose_name=(u"ĐTDĐ"), max_length=14, blank=True, default="")
    def __unicode__(self):
        return self.nom
# Create your models here.
class Poudre(models.Model):
    nom = models.CharField(max_length=200, null=False, blank=False)
    codeP = models.CharField(max_length=200, unique=True)
    fournisseur = models.ForeignKey(Fournisseur,verbose_name=(u"Nhà cung cấp")) 
    date_creation = models.DateTimeField(verbose_name=(u"Ngày tạo bột"), null=True, blank=True,auto_now_add=True)
    date_modification_action = models.DateTimeField(verbose_name=(u"Ngày thay đổi cuối cùng"), auto_now=True, auto_now_add=False)
    instock = models.FloatField(default=0)
    
    def __unicode__(self):
        return self.nom
    
class Type_Event (models.Model):
    nomTE = models.CharField(max_length=200)
    def __unicode__(self):
        return self.nomTE
   
class Event(models.Model):
    poudre = models.ForeignKey(Poudre,verbose_name=(u"Bột"),null=False, blank=False)
    TE = models.ForeignKey(Type_Event,null=False, blank=False)
    date_creation = models.DateTimeField(verbose_name=(u"Ngày tạo"), null=True, blank=True,auto_now_add=True)
    quantite = models.FloatField(verbose_name=(u"Số lượng"),blank=False)
    prix = models.FloatField(verbose_name=(u"Giá"),blank=False)
    somme = models.FloatField(verbose_name=(u"Tổng tiền"))
    commande = models.ForeignKey(Commande, verbose_name=(u"Đơn hàng"),null=False, blank=False)
    commentaires = models.TextField(verbose_name=(u"Ghi chú"))
    instock = models.FloatField(verbose_name=(u"Tồn kho"))
        
    def __unicode__(self):
        return self.TE.nomTE + self.poudre.nom
    
    def update(self):
        p = self.poudre
        if (self.TE.nomTE  == "Xuất"):
            p.instock -= self.quantite
        elif (self.TE.nomTE  == "Nhập"):
            p.instock += self.quantite
        p.save()
        self.instock = p.instock
        self.save()
        return True
        

